package com.smartResponse;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class AddEvent extends Activity {
    EventDB db = new EventDB(this);
	//	private static final int PICK_CONTACT = 0;
		@Override
		@SuppressWarnings({ "rawtypes", "unchecked" })
		public void onCreate(Bundle savedInstanceState) {
		    super.onCreate(savedInstanceState);
		    setContentView(R.layout.addeventlayout);
		    Spinner spinner = (Spinner) findViewById(R.id.locations);
		    ArrayAdapter locations_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		    locations_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		    
		    locations_adapter.add("None");
		    db.open();
	        Cursor cursor = db.getAllLocations();
	        while (cursor.moveToNext()){
	            String location = cursor.getString(1);
	            locations_adapter.add(location);
	        }
	        db.close();
	        spinner.setAdapter(locations_adapter);

	        on_OK_Button_Click();
	        on_Cancel_Button_Click();
	}
		

		public void on_OK_Button_Click() {
			
			Button Button = (Button) findViewById(R.id.m_ok);
			Button.setOnClickListener(new OnClickListener() {
	 
				public void onClick(View v) {

					//The code below stores the text in the box to a string
				    EditText name = (EditText) findViewById(R.id.m_name);
				    EditText message= (EditText) findViewById(R.id.m_message);
				    EditText frequency = (EditText) findViewById(R.id.m_frequency);
				    
		        	String et_name = name.getText().toString();
					String et_message = message.getText().toString();
					String et_frequency = frequency.getText().toString();				 	        		
	        		
				    boolean name_is_valid = true;
				    boolean location_used = true;
				    boolean frequency_valid = true;
				    boolean valid_message = true;
				    db.open();
			        Cursor c = db.getAllMessages();
			        while (c.moveToNext()){
			            String results = c.getString(1);
			            if (results.equals(et_name)){ 	
			            	 name_is_valid=false;
			            }
			        }
			        if  (et_name == null || et_name.isEmpty()){
			        	name_is_valid = false;
			        }
				
			        db.close();
			        if (name_is_valid == true){	
			            Spinner mySpinner = (Spinner)findViewById(R.id.locations);
			            String l_name = mySpinner.getSelectedItem().toString();	
			            //checks if the location is in use
					    db.open();
				        Cursor c2 = db.getAllMessages();
				        while (c2.moveToNext()){
				            String loc = c2.getString(5);
				            if (loc.equals(l_name)){
				            	if (l_name != "None"){
				            		location_used = false;				            		
				            	}

				            	}
				        }
				        db.close();
				        //checks if frequency is valid
			        	if (et_frequency == null || et_frequency.isEmpty()) {
			        		frequency_valid = false;
			        		} else {
			        		   try {
			        		     @SuppressWarnings("unused")
								double num = Double.parseDouble(et_frequency);
			        		   }
			        		   catch (NumberFormatException e) {
			        			   frequency_valid = false;
			        		   }
			        		}
			        		
				        if (location_used == true){	
				        	if (frequency_valid == true){
					        	if (et_message.isEmpty()) {
					        		frequency_valid = false;
					        		}
				        		if (valid_message == true){
									InsertMessage(et_name,et_message,et_frequency,l_name);
									SmartResponseActivity.setCurrentTab(1);
									Intent home_intent_menu = new Intent(AddEvent.this, SmartResponseActivity.class);
									startActivity(home_intent_menu);
									finish();
				        		}
				        		if (valid_message == false){
						        	Context context = getApplicationContext();
						        	CharSequence text = "Please enter a valid message and try again.";
						        	int duration = Toast.LENGTH_LONG;
						        	Toast toast = Toast.makeText(context, text, duration);
						        	toast.show();			
				        		}
								
				        	}
				        	if (frequency_valid == false){
					        	Context context = getApplicationContext();
					        	CharSequence text = "Please enter a time, in seconds, that you would like to wait before sending a reponse between recieved messages.";
					        	int duration = Toast.LENGTH_LONG;
					        	Toast toast = Toast.makeText(context, text, duration);
					        	toast.show();				        	
					        }

				        }
				        if (location_used == false){	
				        	Context context = getApplicationContext();
				        	CharSequence text = "There is already a message event associated with the selected location."+ "\n\n" +
				        	"Please edit the message event associated with this location, or change the location.";
				        	int duration = Toast.LENGTH_LONG;
				        	Toast toast = Toast.makeText(context, text, duration);
				        	toast.show();
				        }
			        }
			        if (name_is_valid == false){	
			        	Context context = getApplicationContext();
			        	CharSequence text = "That name is already in use or is invalid, please enter a different name";
			        	int duration = Toast.LENGTH_LONG;
			        	Toast toast = Toast.makeText(context, text, duration);
			        	toast.show();
			        }
				}

			} );
	}
		public void on_Cancel_Button_Click() {
			 
			Button Button = (Button) findViewById(R.id.m_cancel);
	 
			Button.setOnClickListener(new OnClickListener() {
	 
				public void onClick(View v) {
					SmartResponseActivity.setCurrentTab(1);
					  Intent home_intent_menu = new Intent(AddEvent.this, SmartResponseActivity.class);
					  startActivity(home_intent_menu);
					  finish();
				}

			} );
	}
		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event)  {
		    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
				SmartResponseActivity.setCurrentTab(1);
				  Intent home_intent_menu = new Intent(AddEvent.this, SmartResponseActivity.class);
				  startActivity(home_intent_menu);
				  finish();
		        return true;
		    }

		    return super.onKeyDown(keyCode, event);
		}
		
		
		public void InsertMessage(String name, String message, String frequency, String l_name)
	    {
	    	EventDB db = new EventDB(this);
	        db.open();        
	        db.insertMessage(
	        		name,
	        		message,
	        		frequency,
	        		"Null",
	        		l_name);    
	        db.close();
	    	
	    } 
		//The code in the function below checks to see if a new location was added and if so it refreshes the page
	    @Override
	    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	        super.onActivityResult(requestCode, resultCode, data);
	        
	        if(resultCode==1){
Intent refresh = new Intent(AddEvent.this, AddEvent.class);
	            this.finish();
	            startActivity(refresh);

	        }
	        if(resultCode==RESULT_CANCELED){
	            Intent refresh = new Intent(AddEvent.this, AddEvent.class);
	            startActivity(refresh);
	            this.finish();
	        }
	        
	    }
//Menu Layout
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			super.onCreateOptionsMenu(menu);
			menu.add(0,1,0,"Home").setIcon(R.drawable.home);
	        menu.add(0,2,0,"Save").setIcon(R.drawable.add_icon);
	        menu.add(0,3,0,"Cancel").setIcon(R.drawable.cancel);
		    return true;
		}
	    @Override
	     public boolean onOptionsItemSelected(MenuItem item) {
	        switch (item.getItemId()) {
	        case 1:
			  Intent home_intent_menu = new Intent(AddEvent.this, MainActivity.class);
			  startActivity(home_intent_menu);
			  return true;
	        case 2:
	        	on_OK_Button_Click();
	        	return true;
	     case 3:
	    	 	on_Cancel_Button_Click();
	            return true;
	          }
			return false;
	    }
}
	